<template>
	<view class="container">
		<view class="page-banner">
			<view class="title">
				<view class="left">
					<text>答题进度</text>
					<text class="num"><text class="big">{{ doneNum }}</text>/{{ paperTotal }}</text>
				</view>
				<view class="right">
					<image class="time" src="/static/images/online-examination/time.png"></image>
					<text class="text">剩余时间</text>
					<text>{{ countDown }}</text>
				</view>
			</view>
			<u-line-progress class="progress" v-if="percent" :percentage="percent" :showText="false"
				active-color="#ffffff" inactive-color="#a0c3d0" height="8"></u-line-progress>
			<view class="grid-body">
				<view class="flex info items-center">
					<view class="type">{{currentExam.typeLabel}}</view>
					<view>({{currentExam.score}}分)</view>
				</view>
				<view> </view>
				<view class="content">{{ currentExam.content }}</view>
				<view v-for="(item, index) in currentExam.optionList" :key="index" class="option"
					:class="{ active: isSelect(item) }" @click="handleSelect(item)">
					<text v-if="currentExam.type==='3'">{{ item.content }}</text>
					<text v-else>{{ item.options }}.{{ item.content }}</text>
					<image v-if="isSelect(item)" src="/static/images/online-examination/select.png"></image>
				</view>

				<view class="btn-group">
					<view class="big-btn preview" @click="handlePreview">上一题</view>
					<view class="big-btn next" @click="handleNext">{{ isLastTopic ? '交卷' : '下一题' }}</view>
				</view>
			</view>
		</view>
		<view class="page-footer flex-space-between">
			<view class="answer-sheet" @click="handlePopup">
				<image src="/static/images/online-examination/answer-sheet.png"></image>
				答题卡
			</view>
			<view class="btn-group">
				<!-- <view class="big-btn pause" @click="handlePause">暂停</view> -->
				<view class="big-btn submit" @click="tipDialogVisible = true">交卷</view>
			</view>
		</view>

		<OnlineExamTipDialog v-model="tipDialogVisible" @confirm="handleSubmit(false)" :type="noDoneNum ? '' : 'primary'">
			<view>{{ noDoneNum ? '温馨提示' : '恭喜您' }}</view>
			<view>{{ noDoneNum ? `您还有${noDoneNum}题未做，确认交卷吗` : '题目已全部答完，确认交卷吗' }}</view>
		</OnlineExamTipDialog>
		<OnlineExamTipDialog v-model="outTimeDialogVisible" @confirm="handleSubmit(true)"
			:type="noDoneNum ? '' : 'primary'" timeout>
			<view>温馨提示</view>
			<view>考试超时，自动交卷</view>
		</OnlineExamTipDialog>
		<examination-dialog v-model="examinationDialogVisible" :status="examinationDialogStatus"
			:data="examinationResult" @confirm="tipDialogVisible = true" @ended="handleEnded" @cancel="handleInterval">
		</examination-dialog>
	</view>
</template>

<script>
	import {
		getSimulationTestDetail,
		submitOneExam,
		submitExam
	} from '@/api/educational-training/simulation-test.js'
	import {
		get,
		includes
	} from 'lodash'
	import {
		mapMutations,
		mapState,
		mapActions
	} from 'vuex'
	import {
		examinationStatus
	} from '@/utils/constant'
	import ExaminationDialog from "../online-examination/components/ExaminationDialog.vue";
	import OnlineExamTipDialog from "../online-examination/components/OnlineExamTipDialog";
	import dayjs from "dayjs"

	export default {
		name: 'take-part-examination',

		props: {},

		data() {
			return {
				outTimeDialogVisible: false,
				paperList: [],
				examinationStatus,
				id: '',
				testPaperData: {},
				timer: null,
				examinationDialogStatus: examinationStatus.PAUSE,
				examinationDialogVisible: false,
				examinationResult: {},
				tipDialogVisible: false,
				isSubmit: false, // 是否已提交（防止多次提交）
				examDuration: 0, // 考试总时间(秒)
				isStart: false
			}
		},

		components: {
			ExaminationDialog,
			OnlineExamTipDialog,
		},

		computed: {
			...mapState({
				examDetailList: (state) => state.onlineExam.examDetailList,
				currentPaperIndex: (state) => state.onlineExam.currentPaperIndex
			}),
			countDown() {
				return this.exchangeIntToTimeString(this.examDuration)
			},
			currentExam() {
				return this.paperList[this.currentPaperIndex] || {}
			},
			// paperList() {
			// 	return [
			// 		...get(this.testPaperData, 'singleList', []),
			// 		...get(this.testPaperData, 'multipleList', []),
			// 		...get(this.testPaperData, 'judgementList', [])
			// 	]
			// },
			paperTotal() {
				return get(this.paperList, 'length', 0)
			},
			percent() {
				return Math.floor((this.doneNum) * 100 / this.paperTotal)
			},
			doneNum() {
				return this.paperTotal - this.noDoneNum
			},
			noDoneNum() {
				return this.examDetailList.filter(item => !item.selectOptionIds.length).length
			},
			// 是否为最后一题
			isLastTopic() {
				return this.currentPaperIndex + 1 >= this.paperTotal
			}
		},
		created() {},

		onLoad({
			id
		}) {
			this.id = id
			this.clearStore()
			this.startExam()
		},

		destroyed() {
			clearInterval(this.timer)
		},

		methods: {
			...mapActions(['submitPapel']),
			...mapMutations(['setExamDetailListItem', 'setExamDetailList', 'setCurrentPaperIndex', 'clearStore']),
			async startExam() {
				const {
					data,
					code
				} = await getSimulationTestDetail(this.id)
				this.testPaperData = data
				uni.setNavigationBarTitle({
					title: this.testPaperData.planName
				})
				for (let i of this.testPaperData.questionTypes) {
					for (let j of i.questionList) {
						j.type = i.questionType
						j.typeLabel = i.questionTypeLabel
						j.score = i.score
						this.paperList.push(j)
					}
				}
				this.setExamDetailList(
					this.paperList.map((item) => ({
						selectOptionIds: item.type === '2' ? item.selectOptionIds : (item.selectOptionId ?
							[item.selectOptionId] : []),
						questionId: item.questionId,
						score: item.score
					}))
				)
				this.examDuration = this.exchangeTimeRange(new Date(), new Date(this.testPaperData.endTime))
				this.handleInterval()
			},
			exchangeTimeRange(t1, t2) {
				if (parseInt(t2 - t1) <= 0) {
					return 0
				}
				return parseInt(t2 - t1) / 1000
			},
			handleInterval() {
				this.timer = setInterval(() => {
					this.examDuration--
					if (this.examDuration <= 0) {
						clearInterval(this.timer)
						//TODO 考试结束
						this.outTimeDialogVisible = true
						this.examinationDialogStatus = examinationStatus.PAUSE
					}
				}, 1000)
			},
			handlePreview() {
				if (this.currentPaperIndex > 0) {
					this.eachExamSubmit()
					this.setCurrentPaperIndex(this.currentPaperIndex - 1)
				}
			},
			handleNext() {
				if (this.currentPaperIndex + 1 < this.paperTotal) {
					this.eachExamSubmit()
					this.setCurrentPaperIndex(this.currentPaperIndex + 1)
				} else {
					this.tipDialogVisible = true
				}
			},
			// 每题提交
			eachExamSubmit() {
				let selectOptionIds = get(this.examDetailList, `${this.currentPaperIndex}.selectOptionIds`, [])
				const params = {
					// examTime: this.exchangeIntToTimeString((Number(this.testPaperData.examDuration) * 60) - this
					// 	.examDuration),
					id: this.currentExam.id,
					optionIds: selectOptionIds

				}
				return submitOneExam(this.id, params)
			},
			isSelect({
				id
			}) {
				const currentselectOptionIds = get(this.examDetailList, `${this.currentPaperIndex}.selectOptionIds`,
					[])
				return currentselectOptionIds.includes(id)
			},
			handleSelect({
				id
			}) {
				let selectOptionIds = get(this.examDetailList, `${this.currentPaperIndex}.selectOptionIds`, [])
				if (this.currentExam.type === '2') {
					if (includes(selectOptionIds, id)) {
						if (selectOptionIds.length <= 1) return
						selectOptionIds = selectOptionIds.filter((id) => id !== id)
					} else {
						selectOptionIds.push(id)
					}
				} else {
					selectOptionIds = [id]
				}

				this.setExamDetailListItem({
					questionId: this.currentExam.questionId,
					score: this.currentExam.score,
					selectOptionIds: selectOptionIds
				})
			},
			handlePopup() {
				this.eachExamSubmit()
				uni.navigateTo({
					url: `/pages/work/mock-test/mock-test-answer-sheet?id=${this.id}`
				})
			},
			async handleSubmit(isTimeout) {
				if(!isTimeout) {
					// 先提交当前页的题目(超时会提交失败，无意义)
					await this.eachExamSubmit()
				}

				// 快速点击会导致重复提交
				if (this.isSubmit) {
					return
				}
				this.isSubmit = true
				try {
					await submitExam(this.id)
				} catch (err) {
					console.log(err)
				}
				// 清除定时器
				clearInterval(this.timer)

				getSimulationTestDetail(this.id).then(({
					data
				}) => {
					if (data.score < data.passScore) {
						this.examinationDialogStatus = examinationStatus.FAIL
					} else {
						this.examinationDialogStatus = examinationStatus.SUCCESS
					}
					this.examinationResult = {
						score: data.score,
						errors: data.errorCount,
						qualifying: this.testPaperData.passScore
					}
					this.examinationDialogVisible = true
				}).finally(() => {
					this.isSubmit = false
				})
			},
			handleEnded() {
				// uni.redirectTo({ url: `/pages/work/online-examination/index` })
				uni.navigateBack({delta: 2})
			},
			handlePause() {
				this.eachExamSubmit()
				this.examinationDialogStatus = examinationStatus.PAUSE
				this.examinationDialogVisible = true
				clearInterval(this.timer)
			},
			exchangeIntToTimeString(secNum) {
				let h = parseInt(secNum / 3600)
				h = h < 10 ? `0${h}` : h
				let m = parseInt((secNum % 3600) / 60)
				m = m < 10 ? `0${m}` : m
				let s = parseInt((secNum % 3600) % 60)
				s = s < 10 ? `0${s}` : s
				return `${h}:${m}:${s}`
			}
		}
	}
</script>

<style>
	page {
		height: 100%;
	}
</style>
<style scoped lang="scss" type="text/scss">
	.container {
  background-color: #88b4c4;
  position: relative;
  height: 100%;
  overflow-y: auto;
  padding-bottom: 180rpx;
}
.page-banner {
  padding: 0 30rpx;
  .title {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    font-size: 12px;
    color: #ffffff;

    .right {
      .time {
        transform: translateY(10%);
        width: 26rpx;
        height: 26rpx;
      }
      > text {
        padding-left: 10rpx;
      }
      .text {
        color: #dfe8eb;
      }
    }
    .num {
      padding-left: 20rpx;
      .big {
        font-size: 56rpx;
      }
    }
  }
  .progress {
    margin-top: 16rpx;
  }
  .grid-body {
    margin: 60rpx 0 0;
    padding: 30rpx;
    color: #333333;

    .type {
      width: 100rpx;
      height: 50rpx;
      line-height: 50rpx;
      background: #88b4c4;
      border-radius: 10rpx 10rpx 10rpx 10rpx;
      color: #fff;
      font-size: 12px;
      text-align: center;
    }

    .content {
      margin-top: 30rpx;
      margin-bottom: 40rpx;
      font-size: 30rpx;
      font-weight: bold;
      word-break: break-all;
    }

    .option {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding:30rpx 30rpx 30rpx 20rpx;
      width: 100%;
      // min-height: 88rpx;

      background: #f5f5f5;
      border-radius: 10rpx 10rpx 10rpx 10rpx;
      margin-bottom: 20rpx;
      font-size: 30rpx;

      & text{
        display: inline-block;
        min-height: 48rpx;
        line-height: 48rpx;
      }
      &.active {
        background: #ebf2f5;
      }
      image {
        width: 48rpx;
        height: 48rpx;
        flex-shrink: 0;
      }
    }
    .btn-group {
      margin-top: 40rpx;
    }
    .preview {
      width: 300rpx;
      background-color: #fff;
      color: #88b4c4;
      border: 1px solid #88b4c4;
    }
    .next {
      width: 300rpx;
      color: #fff;
      background-color: #88b4c4;
    }
  }
}
.page-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 158rpx;
  background-color: #fff;
  padding-right: 30rpx;
  padding-left: 46rpx;

  .answer-sheet image {
    display: block;
    margin: 0 auto 5rpx;
    width: 54rpx;
    height: 54rpx;
  }
  .pause {
    width: 231rpx;
    color: #fff;
    background: #c4c088;
  }
  .submit {
    margin-left: 30rpx;
    width: 231rpx;
    color: #fff;
    background: #454a5e;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;

  .big-btn {
    border-radius: 44rpx 44rpx 44rpx 44rpx;
    font-size: 34rpx;
    text-align: center;
    height: 88rpx;
    line-height: 88rpx;
  }
}
</style>
